/**
 * useCornerstone3D Composable
 * 
 * 用于初始化和管理 Cornerstone3D 实例的 Vue 组合式函数
 * 
 * @author yangzhixin
 * @module composables/useCornerstone3D
 */

import { ref, onMounted, onUnmounted, type Ref } from 'vue';
import { CornerstoneFacade } from 'js-3d-model';
import type { ErrorCode } from 'js-3d-model';

/**
 * Cornerstone3D 配置接口
 */
export interface CornerstoneConfig {
  /** 渲染引擎ID */
  renderingEngineId?: string;
  /** 最大缓存大小(MB) */
  maxCacheSize?: number;
  /** 启用GPU渲染 */
  useGPURendering?: boolean;
  /** 启用性能监控 */
  enablePerformanceMonitor?: boolean;
  /** DICOMweb 服务器配置 */
  dicomWebConfig?: {
    baseUrl: string;
    authToken?: string;
  };
}

/**
 * useCornerstone3D 返回类型
 */
export interface UseCornerstone3DReturn {
  /** Cornerstone Facade 实例 */
  facade: Ref<CornerstoneFacade | null>;
  /** 是否已初始化 */
  isInitialized: Ref<boolean>;
  /** 是否正在初始化 */
  isInitializing: Ref<boolean>;
  /** 错误信息 */
  error: Ref<string | null>;
  /** 错误代码 */
  errorCode: Ref<ErrorCode | null>;
  /** 初始化 Cornerstone */
  initialize: (config?: CornerstoneConfig) => Promise<void>;
  /** 销毁 Cornerstone */
  destroy: () => Promise<void>;
  /** 重新初始化 */
  reinitialize: (config?: CornerstoneConfig) => Promise<void>;
}

/**
 * useCornerstone3D - Cornerstone3D 初始化和配置
 * 
 * 提供响应式的 Cornerstone3D 实例管理，处理生命周期和错误
 * 
 * @param autoInit - 是否在组件挂载时自动初始化，默认为 true
 * @param initialConfig - 初始配置
 * @returns Cornerstone3D 实例和相关方法
 * 
 * @example
 * ```vue
 * <script setup>
 * import { useCornerstone3D } from '@/composables/useCornerstone3D';
 * 
 * const { facade, isInitialized, error, initialize } = useCornerstone3D(false);
 * 
 * onMounted(async () => {
 *   await initialize({
 *     maxCacheSize: 512,
 *     useGPURendering: true
 *   });
 * });
 * </script>
 * ```
 */
export function useCornerstone3D(
  autoInit: boolean = true,
  initialConfig?: CornerstoneConfig
): UseCornerstone3DReturn {
  // 响应式状态
  const facade = ref<CornerstoneFacade | null>(null);
  const isInitialized = ref(false);
  const isInitializing = ref(false);
  const error = ref<string | null>(null);
  const errorCode = ref<ErrorCode | null>(null);

  /**
   * 初始化 Cornerstone3D
   * 
   * @param config - 配置选项
   */
  const initialize = async (config?: CornerstoneConfig): Promise<void> => {
    // 防止重复初始化
    if (isInitializing.value || isInitialized.value) {
      console.warn('[useCornerstone3D] 已经初始化或正在初始化中');
      return;
    }

    try {
      isInitializing.value = true;
      error.value = null;
      errorCode.value = null;

      console.log('[useCornerstone3D] 开始初始化 Cornerstone3D...');

      // 合并配置
      const finalConfig = { ...initialConfig, ...config };

      // 创建 Facade 实例
      // 注意：CornerstoneFacade 期望的配置结构
      const facadeInstance = new CornerstoneFacade({
        rendering: {
          useCPURendering: finalConfig.useGPURendering === false, // 注意：这里是反向的
          renderingEngineMode: 'contextPool',
          webGlContextCount: 7
        },
        imageLoader: {
          maxCacheSize: finalConfig.maxCacheSize || 512
        },
        state: {
          enableHistory: true
        },
        error: {
          enableRetry: true,
          maxRetries: 3
        },
        async: {
          concurrency: 3
        }
      });

      // 初始化
      await facadeInstance.initialize();

      // 配置 DICOMweb（如果提供）
      if (finalConfig.dicomWebConfig) {
        await facadeInstance.configureDICOMweb({
          baseUrl: finalConfig.dicomWebConfig.baseUrl,
          authToken: finalConfig.dicomWebConfig.authToken,
        });
      }

      facade.value = facadeInstance;
      isInitialized.value = true;

      // 调试：检查 facade 实例的方法
      console.log('[useCornerstone3D] Cornerstone3D 初始化成功');
      console.log('[useCornerstone3D] facade 实例类型:', typeof facadeInstance);
      console.log('[useCornerstone3D] createViewport 方法:', typeof facadeInstance.createViewport);
      console.log('[useCornerstone3D] facade 原型方法:', Object.getOwnPropertyNames(Object.getPrototypeOf(facadeInstance)).slice(0, 15));
    } catch (err: any) {
      console.error('[useCornerstone3D] 初始化失败:', err);
      error.value = err.message || '初始化失败';
      errorCode.value = err.code || 'INITIALIZATION_ERROR';
      
      // 清理失败的实例
      if (facade.value) {
        try {
          await facade.value.destroy();
        } catch (destroyErr) {
          console.error('[useCornerstone3D] 清理失败的实例时出错:', destroyErr);
        }
        facade.value = null;
      }
      
      throw err;
    } finally {
      isInitializing.value = false;
    }
  };

  /**
   * 销毁 Cornerstone3D 实例
   */
  const destroy = async (): Promise<void> => {
    if (!facade.value) {
      return;
    }

    try {
      console.log('[useCornerstone3D] 销毁 Cornerstone3D...');
      await facade.value.destroy();
      facade.value = null;
      isInitialized.value = false;
      error.value = null;
      errorCode.value = null;
      console.log('[useCornerstone3D] Cornerstone3D 已销毁');
    } catch (err: any) {
      console.error('[useCornerstone3D] 销毁失败:', err);
      error.value = err.message || '销毁失败';
      throw err;
    }
  };

  /**
   * 重新初始化
   * 
   * @param config - 新的配置选项
   */
  const reinitialize = async (config?: CornerstoneConfig): Promise<void> => {
    console.log('[useCornerstone3D] 重新初始化...');
    await destroy();
    await initialize(config);
  };

  // 组件挂载时自动初始化
  onMounted(async () => {
    if (autoInit) {
      try {
        await initialize(initialConfig);
      } catch (err) {
        console.error('[useCornerstone3D] 自动初始化失败:', err);
      }
    }
  });

  // 组件卸载时自动销毁
  onUnmounted(async () => {
    if (facade.value) {
      await destroy();
    }
  });

  return {
    facade,
    isInitialized,
    isInitializing,
    error,
    errorCode,
    initialize,
    destroy,
    reinitialize,
  };
}


